import { t } from 'i18next'
import dayjs from '@/plugins/dayjs'
import classNames from 'classnames'
import ReactDOM from 'react-dom'
import React, { useEffect, useMemo, useRef } from 'react'
import { useGlobalStore } from '@/store/global'
import { IMeeting, NodeType } from '../interface'
import { getPhone } from '../translate'
import { StyledCard } from '../style'
import MeetingCardDetail from './MeetingCardDetail'

const LINE_HEIGHT = 25
const CELL_LEFT_WIDTH = 20

const MeetingCard = ({
	meeting,
	columnWidth,
	currentTime,
}: {
	meeting: IMeeting
	columnWidth: number
	currentTime: dayjs.Dayjs
}) => {
	const user = useGlobalStore((state) => state.user)
	const top = meeting.startGrid * LINE_HEIGHT
	const height = meeting.endGrid * LINE_HEIGHT - top
	const popupRef = useRef<NodeType | null>(null)
	const left =
		Math.round(((columnWidth - CELL_LEFT_WIDTH) / Math.pow(meeting.totalSpan, 1.05)) * (meeting.col - 1)) +
		CELL_LEFT_WIDTH
	const width = Math.floor((columnWidth - left) * Math.pow(0.95, meeting.totalSpan - meeting.col))
	const title = useMemo(() => {
		let str =
			t('主题：') +
			meeting.meeting.name +
			' ' +
			t('时间：') +
			dayjs(meeting.meeting.start_time).format('YYYY-MM-DD HH:mm') +
			' - ' +
			(meeting.meeting.permanent_meeting && meeting.meeting.state !== 3
				? ''
				: dayjs(meeting.meeting.end_time).format('YYYY-MM-DD HH:mm')) +
			' ' +
			t('发起人：') +
			meeting.meeting.organizer_name
		str += getPhone(meeting.meeting.work_phone, meeting.meeting.mobile_phone)
		return str
	}, [])
	useEffect(() => {
		const handleDocumentClick = (e: MouseEvent) => {
			const child = e.target as NodeType
			if (popupRef.current && !isChildOf(child, popupRef.current)) {
				renderOrUnMountModal(false)
			}
		}
		document.addEventListener('click', handleDocumentClick)
		return () => {
			document.removeEventListener('click', handleDocumentClick)
		}
	}, [])
	//参数说明:child表示指定某个节点,parent表示child节点是否存在于parent节点中
	const isChildOf = (child: NodeType | null, parent: NodeType) => {
		let myParentNode = child
		while (myParentNode) {
			if (myParentNode === parent) {
				return true
			} else {
				myParentNode = myParentNode.parentNode
			}
		}
		return false
	}
	const onClick = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
		e.stopPropagation()
		renderOrUnMountModal(true, {
			offsetX: e.clientX,
			offsetY: e.clientY,
			meetingMoid: meeting.meeting.meeting_moid,
		})
	}
	const renderOrUnMountModal = (flag: boolean, info?: { offsetX: number; offsetY: number; meetingMoid: string }) => {
		let container = document.querySelector('.card-modal')
		if (flag && info && user?.enable_meeting) {
			ReactDOM.render(
				<MeetingCardDetail
					ref={popupRef}
					offsetX={info.offsetX}
					offsetY={info.offsetY}
					meetingMoid={info.meetingMoid}
					renderOrUnMountModal={renderOrUnMountModal}
				></MeetingCardDetail>,
				container
			)
		} else {
			container && ReactDOM.unmountComponentAtNode(container)
		}
	}
	const wrapCls = classNames({
		'card-wrap': true,
		approving: meeting.meeting.state === 6,
		'not-approved': meeting.meeting.state === 7,
		mine: meeting.meeting.organizer_moid === user?.moid,
		participate: meeting.meeting.organizer_moid !== user?.moid,
		expired: dayjs(meeting.meeting.end_time).isBefore(currentTime),
	})
	return (
		<>
			<StyledCard style={{ top, left, width, height }} onClick={onClick} title={title}>
				<div className={wrapCls}>
					<p className="subject">{meeting.meeting.name}</p>
					<p className="time">{dayjs(meeting.meeting.start_time).format('YYYY-MM-DD HH:mm')} ~</p>
					{(!meeting.meeting.permanent_meeting || meeting.meeting.state === 3) && (
						<p className="time">{dayjs(meeting.meeting.end_time).format('YYYY-MM-DD HH:mm')}</p>
					)}
				</div>
			</StyledCard>
		</>
	)
}
export default MeetingCard
